package com.yuncheng.mcp.service.impl;

import com.yuncheng.mcp.service.MediaService;
import javazoom.jl.player.Player;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.util.concurrent.ExecutorService;

/**
 * @title: MediaServiceImpl
 * @Author: Liuxk
 * @Date: 2025/5/28 11:06
 */
@Service
public class MediaServiceImpl  implements MediaService {

    private Player player;

    @Autowired
    private ExecutorService executorService;

    @Tool(description = "播放音乐")
    public  String playMusic() {
        System.out.println("========开始播放音乐=============");
        executeAsyncPlayMusic();
        return "播放周杰伦的青花瓷中";
    }


    private void executeAsyncPlayMusic() {
        executorService.submit(() -> {
            // 模拟耗时操作
            System.out.println("Async task started by: " + Thread.currentThread().getName());
            try {
                String filePath = "E:\\IdeaCode\\spring-ai-mcp-demo\\spring-ai-mcp-sse-server\\src\\main\\resources\\music\\青花瓷-周杰伦.mp3";
                FileInputStream fis = new FileInputStream(filePath);
                BufferedInputStream bis = new BufferedInputStream(fis);;
                player = new Player(bis);
                player.play();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            System.out.println("Async task completed by: " + Thread.currentThread().getName());
        });
    }


    @Tool(description = "停止播放音乐")
    public  String stopMusic() {
        System.out.println("========停止播放音乐=============");
        executeAsyncStopMusic();
        return "停止播放音乐";
    }


    private void executeAsyncStopMusic() {
        executorService.submit(() -> {
            // 模拟耗时操作
            System.out.println("Async task started by: " + Thread.currentThread().getName());
            if (player != null) {
                player.close();
            }
            System.out.println("Async task completed by: " + Thread.currentThread().getName());
        });
    }









    public static void main(String[] args) {
        MediaServiceImpl mediaService = new MediaServiceImpl();
        System.out.println("========开始播放音乐=============");
        mediaService.playMusic();
        System.out.println("========结束播放音乐=============");
    }
}
